<template>
  <div>
    <div class="search-bar" style="display: flex;width: 500px;padding-bottom: 10px;" >
      <!-- 搜索输入框 -->
      <el-input v-model="dormNumber" style="width: 250px" placeholder="请输入宿舍名...." ></el-input>
      <!-- 查询按钮 -->
      <el-button type="primary" @click="handleSearch" style="margin-left:10px">查询</el-button>
      <!-- 新增按钮 -->
      <el-button type="primary" @click="addDrom">新增宿舍</el-button>
      <el-button type="primary"  @click="exportExcel">导出Excel</el-button>
    </div>

    <!--新增对话框-->
    <el-dialog title="新增宿舍" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <el-form :model="newDormForm" label-width="80px">
        <el-form-item label="宿舍名称">
          <el-input v-model="newDormForm.dormNumber"></el-input>
        </el-form-item>
        <el-form-item label="宿舍地址">
          <el-input v-model="newDormForm.dormAddress"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>


    <el-table border :data="tableData" style="width: 100%">
      <el-table-column prop="dormId" label="宿舍号" width="180" align="center">
      </el-table-column>
      <el-table-column prop="dormNumber" label="宿舍名称" width="250"  align="center">
      </el-table-column>
      <el-table-column prop="dormAddress" label="宿舍地址" width="250"  align="center">
      </el-table-column>
      // 操作
      <el-table-column label="操作" width="520" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

   <!--分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[7, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

  </div>

</template>
<script>
import {getDorm, addDorm,updateDorm,deleteDorm} from "@/api/api";
import XLSX from "xlsx";

export default {
  data() {
    return {
      tableData: [],// 初始化数据
      currentPage: 1,// 初始化当前页码
      total: 0,// 分页总数
      pageSize: 7,//  初始化每页显示数量,
      newDormForm:{
        dormId: '',
        dormNumber: '',
        dormAddress: ''
      },
      dialogVisible: false,// 默认不显示对话框
      dormNumber: '',// 宿舍号
    }
  },
  created() {
    this.fetchData(this.currentPage, this.pageSize);
  },
  methods: {
    // 分页
    fetchData(page, size, dormNumber = '') {
      const params = {
        page: page, // 使用当前页码
        pageSize: size, // 使用每页数量
        dormNumber: dormNumber
      };
      getDorm(params)
          .then(response => {
            if (response.data.code === 1) {
              console.log(response.data.data)
              this.tableData = response.data.data.records;// 赋值给tableData
              this.total = response.data.data.total;// 赋值给total
              console.log(this.tableData)
            } else {
              console.error('获取宿舍数据时出错： ', response.data.msg);
            }
          }).catch(err=>{
            console.log(err)
      })
    },
    // 新增管理员
    addDrom() {
      this.dialogVisible = true;
    },

    /*搜索*/
    handleSearch(){
      this.fetchData(this.currentPage, this.pageSize, this.dormNumber);
    },
    /*新增*/
    handleSubmit(){
      if(this.newDormForm.dormId){
        //如果表单中存在宿舍ID，则执行更新操作
        updateDorm(this.newDormForm)
            .then((response) => {
              if (response.data.code === 1) {
                this.$message.success("更新成功");
                console.log(response.data)
                this.dialogVisible = false;
                this.fetchData(this.currentPage, this.pageSize);
              } else {
                this.$message.error(response.data.msg);
              }
            }).catch(error => {
              console.error("修改宿舍失败:", error);
        })
      }else {
        // 调用 API 添加宿舍
        addDorm(this.newDormForm)
            .then((res) => {
              if (res.data.code === 1) {
                console.log(res.data)
                this.$message.success("添加成功");
                this.dialogVisible = false;
                // 清空表单数据
                this.$refs.adminForm.resetFields();
                // 刷新宿舍列表或重新请求数据
                this.fetchData(this.currentPage, this.pageSize);
              }
            }).catch(error => {
              console.error("添加宿舍失败:", error);
              this.$message.error("添加宿舍失败");
        })
      }

    },

    // 删除
    handleDelete(index, row) {
      this.$confirm("确定删除当前宿舍吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteDorm(row.dormId)
            .then((res) => {
              if (res.data.code === 1) {
                this.$message.success("删除成功");
                this.fetchData(this.currentPage, this.pageSize); // 在删除成功后调用fetchData方法重新获取宿舍
              }else {
                this.$message.error(res.data.msg);
              }
          }).catch(error => {
            console.error("删除宿舍失败:", error);
          this.$message.info("删除宿舍失败")
        })
        })
    },

    // 导出
    exportExcel(){
      const data = this.tableData.map(item =>({
        宿舍号: item.dormId,
        宿舍名称: item.dormNumber,
        宿舍地址: item.dormAddress,
      }));
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(data);
      XLSX.utils.book_append_sheet(wb, ws, '宿舍列表');
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '宿舍列表.xlsx';
      link.click();
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xff;
        }
        return buf;
      }
      this.$message.success("导出成功");
    },


    // 编辑弹窗
    handleEdit(index, row) {
      this.newDormForm = {...row};
      this.dialogVisible = true;
    },


    // 关闭弹窗
    handleClose(){
      this.dialogVisible = false;
      this.fetchData(this.currentPage, this.pageSize)
    },

    // 分页组件
    handleSizeChange(newSize){
      this.pageSize = newSize;
      this.fetchData(this.currentPage, this.pageSize);
    },
    handleCurrentChange(currentPage){
      this.currentPage = currentPage;
      this.fetchData(this.currentPage, this.pageSize);
    },
  }
}

</script>

<style scoped>

</style>